import axios from 'axios'
import store from '../store'
import router from '../router'
import log from './modules/log'
import point from './modules/point'
import staff from './modules/staff'
import member from './modules/member'
import account from './modules/account'
import common from './modules/common'
import station from './modules/station'
import express from './modules/express'
import balance from './modules/balance'
import billing from './modules/billing'
import * as types from '../store/types'
import accountData from './modules/accountData'


axios.defaults.baseURL = process.env.BASE_URL;
// axios.defaults.timeout = process.env.TIMEOUT;

/**
 * 定义请求拦截器
 */
axios.interceptors.request.use(config => {
    const access_token = store.state.account.access_token;

    if (access_token) {
        config.headers.Authorization = `Bearer ${access_token}`;
    }
    return config;
}, error => {
    return Promise.reject(error);
});

/**
 * 定义响应拦截器
 */
axios.interceptors.response.use(response => {
    return response;
}, error => {
    if (error.response) {
        if (error.response.config.url === axios.defaults.baseURL+'an/auth/login') {
            return Promise.reject(error);
        }
        switch (error.response.status) {
            case 401:
                /**
                 * 返回 401 清除token信息并跳转到登录页面
                 */
                store.commit(types.SET_USER);
                store.commit(types.SET_ACCESS_TOKEN);
                router.replace({
                    path: '/login',
                    // query: {redirect: router.currentRoute.fullPath}
                    // query: { redirect: to.fullPath }
                });
                break;
            default:
                return Promise.reject(error);
        }
    }
});

/**
 * 导出API
 */
export default {
    account,
    member,
    accountData,
    log,
    staff,
    point,
    common,
    station,
    express,
    balance,
    billing
}
